package com.ftg.learn.ai;

import com.alibaba.dashscope.aigc.completion.ChatCompletionChunk;
import com.alibaba.dashscope.aigc.completion.ChatCompletionParam;
import com.alibaba.dashscope.aigc.completion.ChatCompletions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Completable;
import io.reactivex.Flowable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author 布衣
 */
public class TestAiChat {
    public static void main(String[] args) {

        //给定key
        Constants.apiKey = "sk-44547a4c94fc4ccdb0c99c0dfdbe5f1d";
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1";

        //创建核心对话对象
        ChatCompletions c = new ChatCompletions();

        //会话历史
        List<Message> history = new ArrayList<>();


        //构建系统角色
        Message sysMess = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个神怪小说家")
                .build();
        history.add(sysMess);

        System.out.println("----=====================----");
        System.out.println("----=====================----");
        System.out.println("----=welcome to kjx chat=----");
        System.out.println("----=====================----");
        System.out.println("----=====================----");
        Scanner sc = new Scanner(System.in);


        while (true) {
            System.out.println("请选择您的操作  e退出");
            String op = sc.next();
            if (op.equals("e")){
                break;
            }
            //构建普通用户
            Message userMess = Message.builder()
                    .role(Role.USER.getValue())
                    .content(op)
                    .build();
            history.add(userMess);

            ChatCompletionParam params = ChatCompletionParam.builder()
                    .messages(history)
                    .model("qwen-plus")
                    .stream(true)
                    .build();
            String resString = callAI(c,params);

            //提示词
            Message assMess = Message.builder()
                    .role(Role.ASSISTANT.getValue())
                    .content(resString)
                    .build();

            history.add(assMess);
        }

    }

    private static String callAI(ChatCompletions chatCompletions, ChatCompletionParam params) {
        StringBuilder fullResponse = new StringBuilder();

        try {
            // 使用流式调用
            Flowable<ChatCompletionChunk> flowable = chatCompletions.streamCall(params);

            System.out.println("AI回复:");
            // 订阅流并处理每个chunk
            flowable.blockingForEach(chunk -> {
                // 获取每个chunk中的内容并打印
                if (chunk.getChoices() != null && !chunk.getChoices().isEmpty()) {
                    ChatCompletionChunk.Choice choice = chunk.getChoices().get(0);
                    if (choice.getDelta() != null && choice.getDelta().getContent() != null) {
                        System.out.print(choice.getDelta().getContent());
                        fullResponse.append(choice.getDelta().getContent());
                    }
                }
            });
            System.out.println();
        } catch (NoApiKeyException | InputRequiredException e) {
            System.err.println("调用AI时发生错误: " + e.getMessage());
        }

        return fullResponse.toString();
    }
}